/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LayoutUpdateActivity.java   
 * @Package com.jiyi.activity.owner   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-9-15 下午5:05:26   
 * @version V1.0     
 */
package com.jiyi.activity.new_maintenance;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.SinglePicActivity;
import com.jiyi.bean.owner.PlanBean;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.inteface.ConfirmPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.ConfirmPopView;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.CheckUtil;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.CameraUtils;
import com.swift.utils.GlideUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * @ClassName: LayoutUpdateActivity
 * @Description:TODO(楼层查看)
 * @author: HYM
 * @date: 2017-9-15 下午5:05:26
 * 
 */
public class LayoutUpdateActivity extends SinglePicActivity implements
		 ConfirmPopInterface {

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	@BindView(R.id.ivPic)
	ImageView ivPic;
	@BindView(R.id.tvBuild)
	TextView tvBuild;
	@BindView(R.id.tvLayout)
	TextView tvLayout;
	@BindView(R.id.etRatio)
	EditText etRatio;
	@BindView(R.id.etLayoutRemark)
	EditText etLayoutRemark;
	

	// 楼层id
	String floorId;
	PlanBean planBean;
	Dialog dialog;
	// 删除弹窗
	ConfirmPopView mConfirmPopView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_layout_update);
		ButterKnife.bind(this);
		init();
	}
	
	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		super.onDestroy();
	}

	private void init() {
		getIntentData();
		setTop();
		setViewStatus();
		mConfirmPopView = new ConfirmPopView(this, this,"需要删除该层所有所有设备点位吗","取消","删除");
		getData();
	}

	private void setViewStatus() {
		etRatio.setTag(R.id.tag_view_empty, "距离比例不能为空");
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-9-19
	 */
	private void getIntentData() {
		floorId = getIntent().getStringExtra("floorId");
	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("floor_id", floorId);
		dialog = showDialog(dialog);
		VolleyRequest.StringRequestPost(getContext(),
				WebApi.MAINTENANCE_OWNER_FLOOR_INFO, "", params,
				new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								planBean = new Gson().fromJson(data,
										PlanBean.class);
								tvTitle.setText(planBean.getBuilding()
										+ planBean.getFloor_no());
								tvBuild.setText(planBean.getBuilding());
								tvLayout.setText(planBean.getFloor_no());
								etLayoutRemark.setText(planBean.getDescribe());
								GlideUtil.loadIntoUseFitWidth(getContext(), planBean.getMap(),
										ivPic);
								etRatio.setText(planBean.getRatio()+"");

							} 
							else if (status.equals("404") && info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
								//清除环信登录
								UserHelp.getInstance().clearUser(AppBase.Context, true);
								return;
							}
							else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	private void setTop() {
		tvTitle.setText("");
		tvSearch.setVisibility(View.GONE);
	}

	public Context getContext() {
		return this;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == CAMARE_CODE && resultCode == RESULT_OK) {
			try {
				GlideUtil.loadIntoUseFitWidth(getContext(), new File(filePath),
						ivPic);
				mConfirmPopView.showPopWindow();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (requestCode == CHOOSE_PICTURE) {
			if (resultCode == RESULT_OK) {
				if (data != null) {
					Uri temp = data.getData();
					filePath = CameraUtils.getImageAbsolutePath(this, temp);
					GlideUtil.loadIntoUseFitWidth(getContext(), new File(
							filePath), ivPic);
					mConfirmPopView.showPopWindow();
				}

			}
		}
	}
	
	@OnClick({ R.id.tvBack, R.id.tvPost, R.id.tvUpload })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvPost:
			if (CheckUtil.checkView(etRatio)) {
				// 执行新增操作
				doPost();
			}
			break;
		case R.id.tvUpload:
			mPickPopView.showPopWindow();
			break;
		default:
			break;
		}
	}
	
	void doPost()
	{
		if (planBean == null) {
			ToastUtil.getInstances().showMsg("数据未加载完成，请重新打开");
			finish();
			return;
		}
		
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put(AppConfig.COMPANY_ID_KEY, planBean.getCompany_id());
		params.put("id", floorId);
		params.put("ratio", etRatio.getText().toString());
		params.put("describe", etLayoutRemark.getText().toString());
		
		PostFormBuilder postForm = OkHttpUtils.post().url(WebApi.MAINTENANCE_OWNER_FLOOR_UPDATE);
		postForm.params(params);
		if (!TextUtils.isEmpty(filePath)) {
			File file = new File(filePath);
			postForm.addFile("map", "shoot_file.jpg", file);
		}

		dialog = showDialog(dialog);
		postForm.build().execute(new StringCallback() {

			@Override
			public void onError(Call arg0, Exception exception, int arg2) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(exception.getMessage());
			}

			@Override
			public void onResponse(String result, int arg1) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						
					} 
					else if (status.equals("404") && info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg("尚未登录或该用户在其他地方登录，请重新登录！");
						//清除环信登录
						UserHelp.getInstance().clearUser(AppBase.Context, true);
						return;
					}
					else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
		});
	}

	@Override
	public void OnDeleteListener() {
		Log.e("dsfds  ", "OnDeleteListener");
		deleteAllEquip();
		mConfirmPopView.hidePopWindow();
	}
	
	void deleteAllEquip()
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("floor_id", floorId);

		VolleyRequest.StringRequestPost(getContext(), WebApi.MAINTENANCE_OWNER_FLOOR_EQUIP_DELETE,
				"", params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

}
